package com.farm.wcp.user.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.farm.authority.FarmAuthorityService;
import com.farm.authority.domain.User;
import com.farm.authority.service.UserServiceInter;
import com.farm.core.auth.domain.LoginUser;
import com.farm.core.page.ViewMode;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBSort;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.query.DataQuery.CACHE_UNIT;
import com.farm.core.sql.result.DataResult;
import com.farm.doc.server.FarmDocManagerInter;
import com.farm.doc.server.FarmDocOperateRightInter;
import com.farm.doc.server.FarmDocRunInfoInter;
import com.farm.doc.server.FarmDocgroupManagerInter;
import com.farm.doc.server.FarmDocmessageManagerInter;
import com.farm.doc.server.FarmFileManagerInter;
import com.farm.parameter.FarmParameterService;
import com.farm.util.validate.ValidUtils;
import com.farm.util.web.FarmFormatUnits;
import com.farm.wcp.know.service.KnowServiceInter;
import com.farm.web.WebUtils;

/**
 * 统计
 * 
 * @author autoCode
 * 
 */
@RequestMapping("/userStatis")
@Controller
public class StatisticsController extends WebUtils {
	@Resource
	private FarmDocgroupManagerInter farmDocgroupManagerImpl;
	@Resource
	private FarmFileManagerInter farmFileManagerImpl;
	@Resource
	private FarmDocManagerInter farmDocManagerImpl;
	@Resource
	private FarmDocRunInfoInter farmDocRunInfoImpl;
	@Resource
	private KnowServiceInter KnowServiceImpl;
	@Resource
	private FarmDocmessageManagerInter farmDocmessageManagerImpl;
	@Resource
	private FarmDocOperateRightInter farmDocOperateRightImpl;
	@Resource
	private UserServiceInter userServiceImpl;

	/**
	 * 用量统计
	 * 
	 * @return
	 */
	@RequestMapping("/lineStatis")
	@ResponseBody
	public Map<String, Object> timeLineStatisAjaxData(HttpSession session) {
		try {
			DataQuery query = new DataQuery();
			query = DataQuery.init(query,
					"(SELECT COUNT(id) AS num,LEFT(ctime,8) AS DATE FROM farm_doc GROUP BY DATE) AS a", "NUM,DATE");
			query.setPagesize(10000);
			query.addSort(new DBSort("DATE", "ASC"));
			query.setCache(Integer.valueOf(FarmParameterService.getInstance().getParameter("config.wcp.cache.long")),
					CACHE_UNIT.second);
			DataResult result = query.search();

			DataQuery queryGood = DataQuery.init(query,
					"(SELECT COUNT(a.id) AS num,LEFT(a.ctime,8) AS DATE FROM farm_doc a LEFT JOIN farm_docruninfo b ON a.RUNINFOID=b.ID WHERE b.EVALUATE>0  GROUP BY DATE) AS a",
					"NUM,DATE");
			queryGood.setPagesize(10000);
			queryGood.addSort(new DBSort("DATE", "ASC"));
			DataResult resultGood = queryGood.search();
			DataQuery queryBad = DataQuery.init(query,
					"(SELECT COUNT(a.id) AS num,LEFT(a.ctime,8) AS DATE FROM farm_doc a LEFT JOIN farm_docruninfo b ON a.RUNINFOID=b.ID WHERE b.EVALUATE<0  GROUP BY DATE) AS a",
					"NUM,DATE");
			queryBad.setPagesize(10000);
			queryBad.addSort(new DBSort("DATE", "ASC"));
			DataResult resultBad = queryBad.search();
			query = DataQuery.init(query,
					"(SELECT COUNT(id) AS num,LEFT(ctime,8) AS DATE FROM farm_doc GROUP BY DATE) AS a", "NUM,DATE");
			query.setPagesize(10000);
			query.addSort(new DBSort("DATE", "ASC"));
			result = query.search();

			List<List<Object>> jsonResultDayNum = new ArrayList<List<Object>>();
			List<List<Object>> jsonResultTotalNum = new ArrayList<List<Object>>();
			List<List<Object>> jsonResultTotalGoodNum = new ArrayList<List<Object>>();
			List<List<Object>> jsonResultTotalBadNum = new ArrayList<List<Object>>();

			for (Map<String, Object> node : result.getResultList()) {
				List<Object> nodeList = new ArrayList<Object>();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				nodeList.add(Long.valueOf(sdf.parse(node.get("DATE").toString()).getTime()));
				nodeList.add(Float.valueOf(node.get("NUM").toString()));
				jsonResultDayNum.add(nodeList);
			}
			Float TotalNum = Float.valueOf(0);
			for (Map<String, Object> node : result.getResultList()) {
				List<Object> nodeList = new ArrayList<Object>();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				nodeList.add(Long.valueOf(sdf.parse(node.get("DATE").toString()).getTime()));
				TotalNum = TotalNum + Float.valueOf(node.get("NUM").toString());
				nodeList.add(TotalNum);
				jsonResultTotalNum.add(nodeList);
			}
			Float TotalGoodNum = Float.valueOf(0);
			for (Map<String, Object> node : resultGood.getResultList()) {
				List<Object> nodeList = new ArrayList<Object>();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				nodeList.add(Long.valueOf(sdf.parse(node.get("DATE").toString()).getTime()));
				TotalGoodNum = TotalGoodNum + Float.valueOf(node.get("NUM").toString());
				nodeList.add(TotalGoodNum);
				jsonResultTotalGoodNum.add(nodeList);
			}
			Float TotalBadNum = Float.valueOf(0);
			for (Map<String, Object> node : resultBad.getResultList()) {
				List<Object> nodeList = new ArrayList<Object>();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				nodeList.add(Long.valueOf(sdf.parse(node.get("DATE").toString()).getTime()));
				TotalBadNum = TotalBadNum + Float.valueOf(node.get("NUM").toString());
				nodeList.add(TotalBadNum);
				jsonResultTotalBadNum.add(nodeList);
			}
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.toString()).returnObjMode();
		}
		return ViewMode.getInstance().returnObjMode();
	}

	@RequestMapping("/goodGroupStatis")
	public ModelAndView goodGroupStatis(HttpSession session) {
		try {
			DataQuery query = new DataQuery();
			query.setPagesize(10);
			query = DataQuery.init(query,
					"( SELECT d.ID   AS ID, d.GROUPNAME AS NAME,d.JOINCHECK as JOINCHECK, SUM(b.PRAISEYES) AS SUMYES FROM FARM_DOC a LEFT JOIN FARM_DOCRUNINFO b ON a.RUNINFOID = b.ID LEFT JOIN FARM_DOCGROUP d ON d.id=a.DOCGROUPID WHERE d.ID IS NOT NULL GROUP BY d.ID,d.GROUPNAME,d.JOINCHECK) g",
					"ID,NAME,SUMYES,JOINCHECK");
			query.addSort(new DBSort("g.SUMYES", "DESC"));
			query.setCache(Integer.valueOf(FarmParameterService.getInstance().getParameter("config.wcp.cache.long")),
					CACHE_UNIT.second);
			DataResult result = query.search();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.toString()).returnModelAndView("");
		}
		return ViewMode.getInstance().returnModelAndView("");
	}

	@RequestMapping("/goodUserStatis")
	public ModelAndView loadgoodUserStatis(HttpSession session) {
		try {
			DataQuery query = new DataQuery();
			query.setPagesize(10);
			query = DataQuery.init(query,
					"( SELECT d.ID AS ID,d.NAME AS NAME,SUM(b.PRAISEYES) AS SUMYES FROM FARM_DOC a LEFT JOIN FARM_DOCRUNINFO b ON a.RUNINFOID = b.ID LEFT JOIN ALONE_AUTH_USER d ON a.CUSER = d.ID GROUP BY d.ID,d.NAME) g",
					"ID,NAME,SUMYES");
			query.addSort(new DBSort("g.SUMYES", "DESC"));
			query.setCache(Integer.valueOf(FarmParameterService.getInstance().getParameter("config.wcp.cache.long")),
					CACHE_UNIT.second);
			DataResult result = query.search();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.toString()).returnModelAndView("");
		}
		return ViewMode.getInstance().returnModelAndView("");
	}

	@RequestMapping("/manyDocUserStatis")
	public ModelAndView manyDocUserStatis(HttpSession session) {
		try {
			DataQuery query = new DataQuery();
			query.setPagesize(10);
			query = DataQuery.init(query,
					"( SELECT b.ID AS ID, b.name AS NAME, COUNT(*) AS NUM FROM FARM_DOC a LEFT JOIN ALONE_AUTH_USER b ON a.CUSER = b.ID GROUP BY b.id,b.NAME) g",
					"ID,NAME,NUM");
			query.addSort(new DBSort("g.NAME", "DESC"));
			query.setCache(Integer.valueOf(FarmParameterService.getInstance().getParameter("config.wcp.cache.long")),
					CACHE_UNIT.second);
			DataResult result = query.search();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.toString()).returnModelAndView("");
		}
		return ViewMode.getInstance().returnModelAndView("");
	}

	@RequestMapping("/userStatis")
	public ModelAndView loadmyStatis(String userid, HttpSession session) {
		try {
			User user;
			if (userid != null && userid.trim().length() > 0) {
				user = userServiceImpl.getUserEntity(userid);
			} else {
				user = userServiceImpl.getUserEntity(getCurrentUser(session).getId());
			}
			if (user.getImgid() != null && user.getImgid().trim().length() > 0) {
				String photourl = farmFileManagerImpl.getFileURL(user.getImgid());
			}
			StringBuffer sql = new StringBuffer();
			sql.append(
					"SELECT a.NAME AS NAME,a.ID AS ID,a.ctime AS ctime,(SELECT COUNT(*) FROM FARM_DOC WHERE cuser=a.ID) num,(SELECT MIN(ctime) FROM FARM_DOC WHERE cuser=a.ID) stime,(SELECT MAX(ctime) FROM FARM_DOC WHERE cuser=a.ID) etime,");
			sql.append(
					"(SELECT SUM(pb.PRAISEYES) FROM FARM_DOC pa LEFT JOIN FARM_DOCRUNINFO pb ON pb.id=pa.RUNINFOID WHERE cuser=a.ID) AS OKNUM,");
			sql.append(
					"(SELECT SUM(pb.PRAISENO) FROM FARM_DOC pa LEFT JOIN FARM_DOCRUNINFO pb ON pb.id=pa.RUNINFOID WHERE cuser=a.ID) AS NONUM,");
			sql.append(
					"(SELECT SUM(pb.EVALUATE) FROM FARM_DOC pa LEFT JOIN FARM_DOCRUNINFO pb ON pb.id=pa.RUNINFOID WHERE cuser=a.ID) AS EVANUM,");
			sql.append(
					"(SELECT SUM(pb.VISITNUM) FROM FARM_DOC pa LEFT JOIN FARM_DOCRUNINFO pb ON pb.id=pa.RUNINFOID WHERE cuser=a.ID) AS VINUM,");
			sql.append(
					"(SELECT COUNT(*) FROM FARM_DOC pa LEFT JOIN FARM_DOCRUNINFO pb ON pb.id=pa.RUNINFOID WHERE cuser=a.ID AND pb.EVALUATE>0) AS GOODNUM,");
			sql.append(
					"(SELECT COUNT(*) FROM FARM_DOC pa LEFT JOIN FARM_DOCRUNINFO pb ON pb.id=pa.RUNINFOID WHERE cuser=a.ID AND pb.EVALUATE<0) AS BADNUM");
			sql.append(" FROM ALONE_AUTH_USER a WHERE a.ID='" + user.getId() + "'");
			DataQuery query = new DataQuery();
			query.setPagesize(10);
			query = DataQuery.init(query, "(" + sql.toString() + ") g",
					"ID,NAME,NUM,OKNUM,NONUM,EVANUM,VINUM,GOODNUM,BADNUM,STIME,ETIME,CTIME");
			query.setNoCount();
			query.setCache(Integer.valueOf(FarmParameterService.getInstance().getParameter("config.wcp.cache.long")),
					CACHE_UNIT.second);
			DataResult result = query.search();
			if (result.getResultList().get(0).get("EVANUM") == null) {
				result.getResultList().get(0).put("EVANUM", 0);
			}
			if (result.getResultList().get(0).get("VINUM") == null) {
				result.getResultList().get(0).put("VINUM", 0);
			}
			if (result.getResultList().get(0).get("OKNUM") == null) {
				result.getResultList().get(0).put("OKNUM", 0);
			}
			if (result.getResultList().get(0).get("NONUM") == null) {
				result.getResultList().get(0).put("NONUM", 0);
			}
			float eva = new Float(result.getResultList().get(0).get("EVANUM").toString());
			float startRight = 5;
			int L4 = (int) Math.floor(eva / (startRight * startRight * startRight));// 125
			float L4m = eva % (startRight * startRight * startRight);
			int L3 = (int) Math.floor(L4m / (startRight * startRight));// 25
			float L3m = L4m % (startRight * startRight);// 25
			int L2 = (int) Math.floor(L3m / startRight);// 5
			float L2m = L3m % startRight;// 5
			int L1 = (int) Math.floor(L2m);// 1
			result.getResultList().get(0).put("L4", L4);
			result.getResultList().get(0).put("L3", L3);
			result.getResultList().get(0).put("L2", L2);
			result.getResultList().get(0).put("L1", L1);
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.toString()).returnModelAndView("");
		}
		return ViewMode.getInstance().returnModelAndView("");
	}

	/**
	 * 好评文章排名
	 * 
	 * @return
	 */
	@RequestMapping("/goodDocStatis")
	public ModelAndView loadgoodDocStatis(HttpSession session) {
		try {
			DataQuery query = new DataQuery();
			query.setPagesize(10);
			query = DataQuery.init(query,
					"FARM_DOC a LEFT JOIN FARM_DOCRUNINFO b ON a.RUNINFOID=b.ID LEFT JOIN FARM_DOCGROUP c ON a.DOCGROUPID=c.ID LEFT JOIN ALONE_AUTH_USER d ON a.CUSER=d.ID",
					"a.title AS title,a.id AS id,c.JOINCHECK AS JOINCHECK,b.EVALUATE AS EVALUATE,c.GROUPIMG AS GROUPIMG,d.IMGID AS PHOTOID,d.NAME AS USERNAME,c.GROUPNAME AS GROUPNAME,a.DOCGROUPID AS GROUPID");
			query.addSort(new DBSort("b.EVALUATE", "DESC"));
			query.setCache(Integer.valueOf(FarmParameterService.getInstance().getParameter("config.wcp.cache.long")),
					CACHE_UNIT.second);
			DataResult result = query.search();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.toString()).returnModelAndView("");
		}
		return ViewMode.getInstance().returnModelAndView("");
	}

	@RequestMapping("/badDocStatis")
	public ModelAndView loadbadDocStatis(HttpSession session) {
		try {
			DataQuery query = new DataQuery();
			query.setPagesize(10);
			query = DataQuery.init(query,
					"FARM_DOC a LEFT JOIN FARM_DOCRUNINFO b ON a.RUNINFOID=b.ID LEFT JOIN FARM_DOCGROUP c ON a.DOCGROUPID=c.ID LEFT JOIN ALONE_AUTH_USER d ON a.CUSER=d.ID",
					"a.title AS title,a.id AS id,c.JOINCHECK AS JOINCHECK,b.EVALUATE AS EVALUATE,c.GROUPIMG AS GROUPIMG,d.IMGID AS PHOTOID,d.NAME AS USERNAME,c.GROUPNAME AS GROUPNAME,a.DOCGROUPID AS GROUPID");
			query.addSort(new DBSort("b.EVALUATE", "ASC"));
			query.setCache(Integer.valueOf(FarmParameterService.getInstance().getParameter("config.wcp.cache.long")),
					CACHE_UNIT.second);
			DataResult result = query.search();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.toString()).returnModelAndView("");
		}
		return ViewMode.getInstance().returnModelAndView("");
	}
}
